import React, { Component } from 'react';
import { Form, Input,Modal,message,Upload,Button,Icon,Cascader} from 'antd';
import axios from 'axios';
import qs from 'qs';

const FormItem = Form.Item;
const formItemLayout = {
        labelCol: { span: 5 },
        wrapperCol: { span: 18 },
};

class alertModal extends Component {

        constructor(props) {
                super(props);
                //console.log(props)
                //console.log("zz")
                this.state= {
                        list:[],
                        previewVisible: false,
                        previewImage: '',
                        fileList: {}
                }
        }
        componentDidMount() {
                this.getClassList()
        }
        getClassList = () => {
                let that=this
                axios.post("/api/?s=Newsclass.getTree")
                    .then(function (response) {
                            let result=response.data.data
                            that.setState(
                                {
                                        list:result.items
                                }
                            )
                    })
                    .catch(function (error) {
                            console.log(error);
                    })
        }

        handleOk = (e) => {
                console.log(e);
                e.preventDefault();
                this.props.form.validateFields((err, values) => {
                        if (!err) {
                                console.log('Received values of form: ', values);
                                console.log(values)
                                let sendJson={
                                        classname:values.classname,
                                        orderNo:values.orderNo
                                }
                                        if(this.props.record.actionType==="mod")
                                        {
                                                sendJson.id=this.props.record.id
                                        }
                                     sendJson.fatheridArr=values.fatheridArr.toString()
                                     sendJson.fatherid=values.fatheridArr[values.fatheridArr.length-1]
                                //判定当有数据上传时候 则数据走fileList中获取，反之则从values中获取
                                     if(JSON.stringify(this.state.fileList)=="{}")
                                     {
                                             sendJson.imgurl=JSON.stringify(values.uploadFileList[0])
                                     }
                                        else
                                     {
                                             sendJson.imgurl=JSON.stringify(this.state.fileList)
                                     }

                                let sendString=qs.stringify(sendJson)
                                if(this.props.record.actionType==="add")
                                {
                                        this.insertRecord(sendString)
                                }
                                else
                                {
                                        this.updateRecord(sendString)
                                }
                        }
                });
        }
        insertRecord=(sendJson)=>{
                let that=this
                axios.post("/api/?s=Newsclass.insert",sendJson)
                    .then(function (response) {
                            let result=response.data
                            if(result.ret===200)
                            {
                               that.handleCancel()
                               that.props.refresh()
                               message.success("添加成功！")
                            }
                            else
                            {
                               message.error(result.msg)
                            }

                    })
                    .catch(function (error) {
                            console.log(error);
                    })
        }

        updateRecord=(sendJson)=>{
                let that=this
                axios.post("/api/?s=Newsclass.update",sendJson)
                    .then(function (response) {
                            let result=response.data
                            if(result.ret===200)
                            {
                                    that.handleCancel()
                                    that.props.refresh()
                                    message.success("修改成功！")
                            }
                            else
                            {
                                    message.error(result.msg)
                            }

                    })
                    .catch(function (error) {
                            console.log(error);
                    })
        }

        handleCancel = (e) => {
                console.log(e);
                this.props.changeStatus()
        }
        normFile = (e) => {
                //console.log('Upload event:', e);
                if (Array.isArray(e)) {
                        return e;
                }
                //当检测到有上传图片的操作时候，将要最新的图片保存的state中同时删除上传的历史图片，在提交表单的时候，
                if(e.fileList.length>0 && e.fileList[e.fileList.length-1].status=="done")
                {
                        //当多余一张图片时 将多余的图片删除
                        if(e.fileList.length>=2)
                        {
                                e.fileList.splice(0,1)
                        }

                        this.setState({fileList: e.fileList[e.fileList.length-1].response.data})
                }
                return e && e.fileList;
        }

        render() {
                const { getFieldDecorator } = this.props.form;
                return (
                    <div>
                            <Modal
                                title={this.props.record.actionType==="add"?"新增":"修改"}
                                visible={this.props.viewModal}
                                onOk={this.handleOk}
                                okText={"确定"}
                                cancelText={"取消"}
                                onCancel={this.handleCancel}
                                destroyOnClose
                            >
                                    <Form>
                                            <FormItem {...formItemLayout} label="分类名称">
                                                    {getFieldDecorator('classname', {
                                                            rules: [{
                                                                    required: true,
                                                                    message: '请输入分类名称',
                                                            }],
                                                    })(
                                                        <Input placeholder="请输入用户名"/>
                                                    )}
                                            </FormItem>

                                           <FormItem
                                                {...formItemLayout}
                                                label="图片上传"
                                            >
                                                    {getFieldDecorator('uploadFileList', {
                                                            valuePropName: 'fileList',
                                                            getValueFromEvent: this.normFile,
                                                            rules: [{
                                                                    required: true,
                                                                    message: '请选择上传',
                                                            }]
                                                    })(
                                                                   <Upload name="file" action="/api/?s=App.Examples_Upload.go"
                                                                           listType="picture">
                                                                           <Button>
                                                                                   <Icon type="upload" /> 点击上传图片
                                                                           </Button>
                                                                   </Upload>
                                                    )}
                                            </FormItem>
                                            <FormItem
                                                {...formItemLayout}
                                                label="父级目录"
                                            >
                                                    {getFieldDecorator('fatheridArr', {
                                                            initialValue: [],
                                                            rules: [{ type: 'array', required: true, message: '请选择父级目录' }],
                                                    })(
                                                        <Cascader options={this.state.list} changeOnSelect placeholder="父级目录"/>
                                                    )}
                                            </FormItem>
                                            <FormItem {...formItemLayout} label="排序编号">
                                                    {getFieldDecorator('orderNo', {
                                                            rules: [{
                                                                    required: true,
                                                                    message: '请输入排序编号',
                                                            }],
                                                    })(
                                                        <Input placeholder="请输入排序编号"/>
                                                    )}
                                            </FormItem>
                                        </Form>
                            </Modal>
                    </div>
                );
        }
}
export default Form.create({
        mapPropsToFields(props) {
                return {
                        classname: Form.createFormField({
                                value: props.record.classname,
                        }),
                        uploadFileList: Form.createFormField({
                                value: props.record.imgurl,
                        }),
                        fatheridArr: Form.createFormField({
                                value: props.record.fatheridArr,
                        }),
                        orderNo: Form.createFormField({
                                value: props.record.orderNo,
                        }),
                };
        },
})(alertModal)